package cn.leonis.leetcode;

/**
 * @Author Tobi
 * @Date 2021-08-13 下午2:21
 * 不是用if-else实现比较两个数字的大小
 */
public class MaximumLcciSolution {

    public static void main(String[] args) {
        MaximumLcciSolution solution = new MaximumLcciSolution();
        System.out.println(solution.maximum(4, 3));
    }

    /**
     * 解法一：位运算，考虑溢出
     * @param a
     * @param b
     * @return
     */
    public int maximum(int a, int b) {
        int k = b - a >>> 31;
        int aSign = a >>> 31, bSign = b >>> 31;
        int diff = aSign ^ bSign;
        k = k & (diff ^ 1) | bSign & diff;
        return a * k + b * (k ^ 1);
    }

    /**
     * 解法二：数学公式
     * @param a
     * @param b
     * @return
     */
    public int maximum1(int a, int b) {
        return (a + b + Math.abs(a - b)) / 2;
    }
}
